
const {
  findApproveById,
  updateApproveById,
  findApproveList,
  getApproveCountByFields
} = require('../model/approve');
const { mkPager } = require('../utils');

exports.submitApprove = async (ctx) => {
  // 查看申请是否存在
  const { id } = ctx.request.body
  const findRes = await findApproveById(id)
  if (findRes.length != 1) return ctx.faild({ msg: '该申请不存在' })
  const { status } = findRes[0]

  let currentState = stateFlow[status]
  currentState = currentState.pass || currentState;

  if (currentState.v == status) return ctx.faild({ msg: '状态无法改变，提交状态相同' })

  const updateRes = await updateApproveById({ status: currentState.v, id })
  if (updateRes.changedRows != 1) return ctx.faild({ msg: '更新失败' })

  return ctx.success({ msg: '提交成功', from: currentState.t })
}

// 通用查询
function list(isFirst) {
  return async ctx => {
    const { name, pageNo, pageSize } = ctx.query
    const status = isFirst ? 1 : 4
    const { limitA, limitB } = mkPager(pageNo, pageSize)
    if (name) {
      var findres = await findApproveList(limitA, limitB, { name, status })
      var countRes = await getApproveCountByFields({ name, status })
    } else {
      var findres = await findApproveList(limitA, limitB, { status })
      var countRes = await getApproveCountByFields({ status })
    }
    console.log(findres);
    if (!findres.length) return ctx.faild({ msg: '查询异常，请稍后重试' })
    const { total } = countRes[0]
    const page = Math.ceil(total / pageSize)
    return ctx.success({
      msg: '查询成功',
      data: findres,
      total,  // 总条数
      page,   // 有多少页
      pageSize: limitB  // 每页大小
    })
  }
}
exports.getFirstApproveList = list(true)
exports.getEndApproveList = list(false)